<template>
  <h1>{{ msg }}</h1>
  <div class="container">
    <Header :addTodo="addTodo" />
    <List :todos="todos" :deleteTodo="deleteTodo" :updateTodo="updateTodo" />
    <Footer
      :todos="todos"
      :checkAll="checkAll"
      :clearAllCompletedTodos="clearAllCompletedTodos"
    />
  </div>
</template>

<script lang="ts">
// import { Options, Vue } from "vue-class-component";
import { defineComponent, onMounted, reactive, toRefs, watch } from "vue";
import Header from "../components/header.vue";
import List from "../components/list.vue";
import Footer from "../components/footer.vue";
// 引入接口
import { Todo } from "../types/todo";
import { saveTodos, readTodos } from "../utils/localStorageUtils";
export default defineComponent({
  props: {
    msg: String,
  },
  components: {
    Header,
    List,
    Footer,
  },
  setup() {
    // 模拟数据
    // const state = reactive<{ todos: Todo[] }>({
    //   todos: [
    //     {
    //       id: 1,
    //       title: "吃饭",
    //       isCompleted: false,
    //     },
    //     {
    //       id: 2,
    //       title: "学习",
    //       isCompleted: false,
    //     },
    //     {
    //       id: 3,
    //       title: "睡觉",
    //       isCompleted: true,
    //     },
    //   ],
    // });
    const state = reactive<{ todos: Todo[] }>({
      todos: [],
    });
    // 页面加载完毕后读取数据
    onMounted(()=>{
      setTimeout(()=>{
        state.todos = readTodos()
      },500)
    })
    // 添加数据的方法
    const addTodo = (todo: Todo) => {
      state.todos.unshift(todo);
    };
    // 删除数据的方法
    const deleteTodo = (index: number) => {
      state.todos.splice(index, 1);
    };
    // 修改isCompleted属性的状态(设置一个方法传给子级组件去调用修改，而不是子级组件直接修改)
    const updateTodo = (todo: Todo, isCompleted: boolean) => {
      todo.isCompleted = isCompleted;
      // console.log(todo);
    };
    // 全选或不全选操作
    const checkAll = (isCompleted: boolean) => {
      // 遍历数组
      state.todos.forEach((todo) => {
        todo.isCompleted = isCompleted;
      });
    };
    // 清除所有选中的数据
    const clearAllCompletedTodos = () => {
      state.todos = state.todos.filter((todo) => !todo.isCompleted);
    };
    // 监视操作：todos数组变化直接存储到浏览器的缓存中
    // watch(
    //   () => state.todos,
    //   (value) => {
    //     saveTodos(value);
    //   },
    //   { deep: true }
    // );
    // 优化代码
    watch(() => state.todos, saveTodos, { deep: true });

    return {
      ...toRefs(state),
      addTodo,
      deleteTodo,
      updateTodo,
      checkAll,
      clearAllCompletedTodos,
    };
  },
});
// @Options({
//   props: {
//     msg: String,
//   },
//   components: {
//     Header,
//     List,
//     Footer,
//   },
// })
// export default class Index extends Vue {
//   msg!: string;
// }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss" src="./scss/index.scss">
</style>
